package com.lw.leetcode.tree.a;

import com.lw.leetcode.tree.TreeNode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

/**
 * 637. 二叉树的层平均值
 *
 * @Author liw
 * @Date 2021/5/12 9:55
 * @Version 1.0
 */
public class AverageOfLevels {

    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        Queue<TreeNode> a = new ArrayDeque<>();
        Queue<TreeNode> b = new ArrayDeque<>();
        a.add(root);
        while (!a.isEmpty()) {
            double sum = 0D;
            int count = 0;
            while (!a.isEmpty()) {
                TreeNode poll = a.poll();
                sum += poll.val;
                count++;
                if (poll.left != null) {
                    b.add(poll.left);
                }
                if (poll.right != null) {
                    b.add(poll.right);
                }
            }
            a = b;
            b = new ArrayDeque<>();
            list.add(sum / count);
        }
        return list;
    }
}
